<template>
  <div class="field-panel">
    <div class="panel-header">
      <h4>字段列表</h4>
      <div class="header-actions">
        <el-select v-model="selectedDataSource" placeholder="选择数据源" size="small" style="width: 150px" @change="onDataSourceChange">
          <el-option 
            v-for="source in dataSources" 
            :key="source.id"
            :label="source.name"
            :value="source.id" />
        </el-select>
        <el-button size="small" @click="refreshFields">刷新</el-button>
      </div>
    </div>
    
    <div class="field-categories">
      <!-- 维度字段 -->
      <div class="field-category">
        <div class="category-header" @click="toggleCategory('dimensions')">
          <el-icon><FolderOpened v-if="expandedCategories.dimensions" /><Folder v-else /></el-icon>
          <span>维度</span>
          <span class="field-count">({{ dimensionFields.length }})</span>
        </div>
        <div v-show="expandedCategories.dimensions" class="field-list">
          <div 
            v-for="field in dimensionFields"
            :key="field.id"
            class="field-item dimension-field"
            draggable="true"
            @dragstart="onDragStart(field, $event)"
            @dragend="onDragEnd"
          >
            <el-icon class="field-icon"><Document /></el-icon>
            <span class="field-name">{{ field.name }}</span>
            <span class="field-type">{{ field.type }}</span>
          </div>
        </div>
      </div>

      <!-- 度量值字段 -->
      <div class="field-category">
        <div class="category-header" @click="toggleCategory('measures')">
          <el-icon><FolderOpened v-if="expandedCategories.measures" /><Folder v-else /></el-icon>
          <span>度量值</span>
          <span class="field-count">({{ measureFields.length }})</span>
        </div>
        <div v-show="expandedCategories.measures" class="field-list">
          <div 
            v-for="field in measureFields"
            :key="field.id"
            class="field-item measure-field"
            draggable="true"
            @dragstart="onDragStart(field, $event)"
            @dragend="onDragEnd"
          >
            <el-icon class="field-icon"><DataAnalysis /></el-icon>
            <span class="field-name">{{ field.name }}</span>
            <span class="field-type">{{ field.type }}</span>
          </div>
        </div>
      </div>
    </div>

    <!-- 搜索框 -->
    <div class="search-section">
      <el-input
        v-model="searchQuery"
        placeholder="搜索字段..."
        clearable
        @input="filterFields"
      >
        <template #prefix>
          <el-icon><Search /></el-icon>
        </template>
      </el-input>
    </div>

    <!-- 搜索结果 -->
    <div v-if="searchQuery" class="search-results">
      <h5>搜索结果</h5>
      <div class="field-list">
        <div 
          v-for="field in filteredFields"
          :key="field.id"
          class="field-item"
          :class="field.category === '维度' ? 'dimension-field' : 'measure-field'"
          draggable="true"
          @dragstart="onDragStart(field, $event)"
          @dragend="onDragEnd"
        >
          <el-icon class="field-icon">
            <Document v-if="field.category === '维度'" />
            <DataAnalysis v-else />
          </el-icon>
          <span class="field-name">{{ field.name }}</span>
          <span class="field-type">{{ field.type }}</span>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, watch, onMounted } from 'vue'
import { useTableStore } from '../stores/tableStore'
import { useDataModelStore } from '../stores/dataModelStore'
import { 
  Folder, 
  FolderOpened, 
  Document, 
  DataAnalysis, 
  Search 
} from '@element-plus/icons-vue'

// 使用store
const tableStore = useTableStore()
const dataModelStore = useDataModelStore()

// 响应式数据
const searchQuery = ref('')
const selectedDataSource = ref('')
const expandedCategories = ref({
  dimensions: true,
  measures: true
})

// 计算属性
const dataSources = computed(() => dataModelStore.dataSources)

const dimensionFields = computed(() => {
  if (selectedDataSource.value) {
    return dataModelStore.dimensionFields.filter(field => 
      field.tableId && getTableDataSource(field.tableId) === selectedDataSource.value
    )
  }
  return tableStore.dimensionFields
})

const measureFields = computed(() => {
  if (selectedDataSource.value) {
    return dataModelStore.measureFields.filter(field => 
      field.tableId && getTableDataSource(field.tableId) === selectedDataSource.value
    )
  }
  return tableStore.measureFields
})

const allFields = computed(() => {
  if (selectedDataSource.value) {
    return dataModelStore.allFields.filter(field => 
      field.tableId && getTableDataSource(field.tableId) === selectedDataSource.value
    )
  }
  return tableStore.fields
})

const filteredFields = computed(() => {
  if (!searchQuery.value) return []
  
  return allFields.value.filter(field => 
    field.name.toLowerCase().includes(searchQuery.value.toLowerCase())
  )
})

// 方法
const getTableDataSource = (tableId) => {
  for (const dataSource of dataSources.value) {
    if (dataSource.tables?.some(table => table.id === tableId)) {
      return dataSource.id
    }
  }
  return null
}

const toggleCategory = (category) => {
  expandedCategories.value[category] = !expandedCategories.value[category]
}

const onDataSourceChange = () => {
  // 数据源切换时的处理
  console.log('切换数据源:', selectedDataSource.value)
}

const onDragStart = (field, event) => {
  // 增强字段信息，包含数据源和表信息
  const enhancedField = {
    ...field,
    dataSourceId: selectedDataSource.value,
    tableName: field.tableName || getTableName(field.tableId)
  }
  
  event.dataTransfer.setData('application/json', JSON.stringify(enhancedField))
  event.dataTransfer.effectAllowed = 'copy'
  
  // 添加拖拽样式
  event.target.classList.add('dragging')
}

const onDragEnd = (event) => {
  event.target.classList.remove('dragging')
}

const getTableName = (tableId) => {
  for (const dataSource of dataSources.value) {
    const table = dataSource.tables?.find(t => t.id === tableId)
    if (table) return table.name
  }
  return ''
}

const filterFields = () => {
  // 搜索逻辑已在计算属性中处理
}

const refreshFields = () => {
  // 刷新字段列表
  dataModelStore.refreshModel()
  console.log('刷新字段列表')
}

// 初始化
onMounted(() => {
  // 如果有数据源，默认选择第一个
  if (dataSources.value.length > 0) {
    selectedDataSource.value = dataSources.value[0].id
  }
})
</script>

<style scoped>
.field-panel {
  height: 100%;
  display: flex;
  flex-direction: column;
  background: white;
  border-right: 1px solid #e4e7ed;
}

.panel-header {
  display: flex;
  flex-direction: column;
  gap: 12px;
  padding: 16px;
  border-bottom: 1px solid #e4e7ed;
}

.panel-header h4 {
  margin: 0;
  color: #303133;
  font-size: 16px;
}

.header-actions {
  display: flex;
  gap: 8px;
  align-items: center;
}

.field-categories {
  flex: 1;
  overflow-y: auto;
  padding: 8px 0;
}

.field-category {
  margin-bottom: 8px;
}

.category-header {
  display: flex;
  align-items: center;
  padding: 8px 16px;
  cursor: pointer;
  background: #f8f9fa;
  border-bottom: 1px solid #e4e7ed;
  transition: background-color 0.2s ease;
}

.category-header:hover {
  background: #e9ecef;
}

.category-header span {
  margin-left: 8px;
  font-weight: 500;
  color: #303133;
}

.field-count {
  margin-left: auto !important;
  font-size: 12px;
  color: #909399;
  font-weight: normal;
}

.field-list {
  padding: 4px 0;
}

.field-item {
  display: flex;
  align-items: center;
  padding: 8px 16px;
  cursor: grab;
  transition: all 0.2s ease;
  border-left: 3px solid transparent;
}

.field-item:hover {
  background: #f0f9ff;
}

.field-item.dragging {
  opacity: 0.5;
  cursor: grabbing;
}

.dimension-field {
  border-left-color: #409EFF;
}

.dimension-field:hover {
  background: #ecf5ff;
}

.measure-field {
  border-left-color: #67C23A;
}

.measure-field:hover {
  background: #f0f9ff;
}

.field-icon {
  margin-right: 8px;
  color: #606266;
}

.field-name {
  flex: 1;
  font-size: 14px;
  color: #303133;
}

.field-type {
  font-size: 12px;
  color: #909399;
  background: #f4f4f5;
  padding: 2px 6px;
  border-radius: 4px;
}

.search-section {
  padding: 16px;
  border-top: 1px solid #e4e7ed;
}

.search-results {
  padding: 0 16px 16px;
}

.search-results h5 {
  margin: 0 0 8px 0;
  color: #303133;
  font-size: 14px;
}

/* 拖拽时的视觉反馈 */
.field-item[draggable="true"]:active {
  cursor: grabbing;
}
</style>